﻿using System;
using System.Diagnostics;
using System.Net;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace BackgroundActionPool_Test {
    [TestClass]
    public class ExceptionText {
        private ManualResetEvent m_waitForAllDoneEvent;
        
        [TestMethod]
        public void Test_Exception () {
            m_waitForAllDoneEvent = new ManualResetEvent(false);
            BackgroundTask.BackgroundActionPool<String, String> pool =
                new BackgroundTask.BackgroundActionPool<string, string>();
            var downloadFile = pool.Create(DownloadFile, "http://not-a-url.tfake/");
            downloadFile.OnDone += downloadFile_OnDone;
            pool.Add(downloadFile);
            pool.OnAllDone += pool_OnAllDone;
            pool.Run();
            m_waitForAllDoneEvent.WaitOne(5000);
        }

        void pool_OnAllDone (object sender, EventArgs e) {
            
        }

        [ExpectedException(typeof(Exception))]
        void downloadFile_OnDone (object sender, BackgroundTask.ActionDoneEventArgs<string> e) {
            Assert.IsTrue(e.IsFailed);
            Debug.WriteLine("Download failed: "+e.Exception.Message);
            m_waitForAllDoneEvent.Set();
            throw e.Exception;
        }

        public String DownloadFile(String file) {
            WebClient clt = new WebClient();
            
            return clt.DownloadString(file);
        }
    }
}
